package cn.akira.trigger.job;

import cn.akira.domain.strategy.model.vo.StrategyAwardStockKeyVO;
import cn.akira.domain.strategy.service.raffle.IRaffleStock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author fjl95
 * @date 2025/5/19
 * @description 更新奖品库存，为了不让更新库存的压力打到数据库中，这里采用了redis跟新缓存内存，异步队列更新数据库，数据库表最终一致即可。
 */
@Slf4j
@Component
public class UpdateAwardStockJob {

    @Resource
    private IRaffleStock raffleStock;

    @Scheduled(cron = "0/5 * * * * ?")
    public void execute() {
        try {
            log.info("定时任务，更新奖品消耗库存【延迟队列获取，降低对数据库的更新频次，不要产生竞争】");
            StrategyAwardStockKeyVO strategyAwardStockKeyVO = raffleStock.takeQueueValue();
            if (strategyAwardStockKeyVO == null) {
                return;
            }
            log.info("定时任务，更新奖品消耗库存 strategyId:{},awardId:{}",strategyAwardStockKeyVO.getStrategyId(),strategyAwardStockKeyVO.getAwardId());
            raffleStock.updateStrategyAwardStock(strategyAwardStockKeyVO.getStrategyId(),strategyAwardStockKeyVO.getAwardId());

        }catch (Exception e) {
            log.error("定时任务，更新奖品消耗库存失败",e);
        }
    }
}
